package cn.crawler.app.crown.modules.services.impl;

import cn.crawler.app.crown.commons.util.DecipherUtil;
import cn.crawler.app.crown.modules.models.CrownEquipment;
import cn.crawler.app.crown.modules.services.CrownEquipmentService;
import cn.crawler.framework.base.service.BaseServiceImpl;
import cn.crawler.framework.util.Id;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.commons.lang3.ArrayUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.plugins.wkcache.annotation.CacheDefaults;
import org.nutz.plugins.wkcache.annotation.CacheRemoveAll;
import org.nutz.plugins.wkcache.annotation.CacheResult;


@IocBean(args = {"refer:dao"})
@Service(interfaceClass = CrownEquipmentService.class)
@CacheDefaults(cacheName = "crown_equipment")
public class CrownEquipmentServiceImpl extends BaseServiceImpl<CrownEquipment> implements CrownEquipmentService {
    public CrownEquipmentServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    @CacheRemoveAll
    public void clearCache() {

    }

    @Override
    @CacheResult(cacheKey = "no_${args[0]}")
    public CrownEquipment fetchByNo(String no) {
        return this.fetch(Cnd.where("no", "=", no)
                .and("disabled", "=", 0)
                .and("delFlag", "=", 0)
        );
    }

    @Override
    public Object data(String searchKeyword, String[] searchDate, int pageNumber, int pageSize) {
        // 根据站点,用户名搜索
        Sql sql = Sqls.create("select * from crown_equipment $condition ");
        Sql countSql = Sqls.create("select count(1) from crown_config $condition ");
        Cnd cnd = Cnd.NEW();
        // 按账号用户名搜索
        if (Strings.isNotBlank(searchKeyword)) {
            cnd.and("no", "=", searchKeyword).or("name", "like", "%" + searchKeyword + "%");
        }
        // 按时间搜索
        if (ArrayUtils.isNotEmpty(searchDate)) {
            cnd.and("opAt", ">=", Times.d2TS(Times.D(searchDate[0])));
            cnd.and("opAt", "<=", Times.d2TS(Times.D(searchDate[1])));
        }
        sql.setCondition(cnd);
        sql.appendSourceSql("order by opAt desc");
        countSql.setCondition(cnd);
        return this.listPage(pageNumber, pageSize, sql, countSql);
    }

    @Override
    public void add(CrownEquipment equipment) throws Exception {
        equipment.setOpAt(1L);
        equipment.setNo(Id.createOrderNo());
        equipment.setSecret(DecipherUtil.generateKey());
        this.insert(equipment);
        this.clearCache();
    }

    @Override
    public void editDo(CrownEquipment equipment) {
        this.update(equipment);
        this.clearCache();
    }

}
